import subprocess
import json
import requests
import time

def get_pid():
    try:
        output = subprocess.check_output(['ps', '-ef'], text=True)
        lines = output.split('\n')
        process = [
            line for line in lines
            if 'temp/qemu_temp/qemu_start_temp/qemu-system-aarch64-release' in line
            and 'grep' not in line
        ]
        pid = [pro.split()[1]
                for pro in process if len(pro.split()) >= 8]
        
        return pid
    except subprocess.CalledProcessError as e:
        print(f"❌ 检测现有qemu运行实例ps命令执行错误：{e}")
        return []
    except Exception as e:
        print(f"❌ 发生未知错误，{e}")
        return []

def close_qemu():
    pid = get_pid()
    print(pid)
    if pid:
        subprocess.run(["kill", "-9", str(pid[-1])], check=True)
        print("✅ qemu已停止")

def get_web(ip, port, auth, uri, header):
    req_url = 'https://{}:{}{}'.format(ip, port, uri)
    start_time = time.time()
    try:
        rsp = requests.get(
            url=req_url, headers=header, auth=auth, verify=False, timeout=(2, 30)
        )
        return rsp, time.time()-start_time
    except requests.exceptions.RequestException as e:
        print(f"web请求失败:{e}")
        return None, time.time()- start_time

def read_config(config_path='config.json'):
    try:
        with open(config_path) as f:
            cfg = json.load(f)
        return cfg
    except Exception as e:
        print(f"⚠️ 读取配置文件失败: {e}, 使用默认端口")
        return {
            "mapports": {
                "https": 443,
                "ssh": 22,
                "ipmi": 623
            }
        }